package com.neusoft.blog.service;

import com.neusoft.blog.bean.RespBean;
import com.neusoft.blog.bean.UserUtile;
import com.neusoft.blog.bean.Userinfo;
import com.neusoft.blog.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserService implements UserDetailsService {
    @Autowired
    UserMapper userMapper;

    public Userinfo login(String username, String password) {
        Userinfo userinfo=userMapper.login(username,password);
        if(userinfo!=null){
            userinfo.setPassword(null);
        }
        return userinfo;
    }

    public List<Userinfo> seletUser() {
        return  userMapper.seletUser();
    }

    public RespBean updeteStatus(Boolean enabled, Integer id) {
        int count =userMapper.updeteStatus(enabled,id);
        if(count>0){
            return RespBean.ok("更改状态成功",null);
        }
        return  RespBean.error("更改状态失败");
    }

    public UserUtile findUser(String loginname) {
        return  userMapper.findUser(loginname);
    }

    public RespBean delUser(Integer id) {
        int count =userMapper.delUser(id);
        if(count>0){
            return RespBean.ok("删除用户成功",null);
        }
        return  RespBean.error("删除用户失败");
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Userinfo user =userMapper.loadUserByUsername(username);
        if(user==null){
            throw new  UsernameNotFoundException("用户不存在");
        }
        user.setRoles(userMapper.getRolesById(user.getId()));
        return user;
    }

}
